<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Goods;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;
use App\Models\Match;
use DB;
use Illuminate\Support\Arr;

class GoodsController extends Controller
{
    use  ApiResponse;

    public function index(Request $request)
    {
        $goods = Goods::query();
        $category = null;
        if ($request['type_id']) {
            $goods->where('type_id', $request['type_id']);
            $category = Category::query()->where('id', $request['type_id'])->first();
        }
        if ($request['k']) {
            $goods->where('name', 'like', '%' . $request['k'] . '%');
        }
        /*if(!$request['k']){
            return alert("请输入关键字");
        }*/
        $goods = $goods->orderBy('goods_id', 'DESC')->paginate(16);
        return view('goods.index', ['goods' => $goods, 'category' => $category]);
    }


    public function show(Request $request)
    {

        $goods = Goods::query()->where('goods_id', $request['id'])->first();
        if (!$goods) {
            return abort(404);
        }

        $goodsMatch = Match::query()->where('goods_id', $goods->goods_id)->get();

        $goodsMatchNumberJson = $goodsMatch->map(function ($item) {
            return Arr::only($item->toArray(), ['num', 'id']);
        });
        return view('goods.show', [
            'goods' => $goods,
            'goodsMatch' => $goodsMatch,
            'goodsMatchNumberJson' => $goodsMatchNumberJson,
        ]);
    }

    public function match(Request $request)
    {
        $id = $request['goods_id'];
        $goodsMatch = Match::query()->where('goods_id', $id)->get();
        return $this->success(['match' => $goodsMatch]);
    }

}
